// Node-RED HTTP Function Node: 查询指定tenant下的多个propId当前值
// 使用前置节点：HTTP In (POST) → Function (本脚本) → HTTP Response

// 支持的输入：
// - Header: tenant-id: <string>
// - Body Payload(JSON):
//   {
//     "propIds": "id1,id2,..." | ["id1","id2",...],
//     "projectId": "p1",                  // 可选，单个项目
//     "projectIds": "p1,p2" | ["p1","p2"] // 可选，多个项目
//   }

function normalizeList(input) {
    if (!input) return [];
    if (Array.isArray(input)) return input.map(String);
    if (typeof input === 'string') {
        return input
            .split(',')
            .map(s => s.trim())
            .filter(s => s.length > 0);
    }
    return [];
}

function normalizePropIds(input) {
    return normalizeList(input);
}

function normalizeProjectIds(projectId, projectIds) {
    const listA = normalizeList(projectId);
    const listB = normalizeList(projectIds);
    const set = new Set([...listA, ...listB]);
    return Array.from(set);
}

function getStore() {
    // 优先使用global，其次使用flow
    return (global.get && global.get('mqttDataStore'))
        || (flow.get && flow.get('mqttDataStore'))
        || {};
}

function getValuesForTenant(store, tenantId, propIds, filterProjectIds) {
    const result = {};
    if (!tenantId || !store[tenantId]) {
        for (const pid of propIds) result[pid] = null;
        return result;
    }

    const projects = store[tenantId];
    const restrict = (filterProjectIds && filterProjectIds.length) ? new Set(filterProjectIds.map(String)) : null;

    // 为每个propId在目标项目集合里查找最新(lastUpdate最大)的一条
    for (const pid of propIds) {
        let best = null;
        for (const projectId in projects) {
            if (restrict && !restrict.has(projectId)) continue;
            const projectData = projects[projectId];
            const entry = projectData && projectData[pid];
            if (!entry) continue;
            if (!best || (entry.lastUpdate || 0) > (best.lastUpdate || 0)) {
                best = entry;
            }
        }
        result[pid] = best ? best.value : null;
    }
    return result;
}

try {
    // 读取header中的tenant-id
    const headers = (msg.req && msg.req.headers) || msg.headers || {};
    const tenantId = headers['tenant-id'] || headers['Tenant-Id'] || headers['Tenant-ID'] || headers['tenant_id'];

    // 读取payload中的propIds和projectId(s)
    let body = {};
    if (msg.payload && typeof msg.payload === 'object') {
        body = msg.payload;
    } else if (typeof msg.payload === 'string') {
        try { body = JSON.parse(msg.payload); } catch (e) { body = { propIds: msg.payload }; }
    }

    const propIds = normalizePropIds(body.propIds);
    const filterProjectIds = normalizeProjectIds(body.projectId, body.projectIds);

    if (!tenantId) {
        msg.statusCode = 400;
        msg.payload = { success: false, message: 'Missing tenant-id header', code: 400, result: {} };
        return msg;
    }
    if (!propIds.length) {
        msg.statusCode = 400;
        msg.payload = { success: false, message: 'Missing propIds in payload', code: 400, result: {} };
        return msg;
    }

    const store = getStore();
    const values = getValuesForTenant(store, String(tenantId), propIds, filterProjectIds);

    msg.statusCode = 200;
    msg.payload = {
        success: true,
        message: '',
        code: 200,
        result: values
    };
    return msg;

} catch (err) {
    node.error('http_query_props error: ' + err.message);
    msg.statusCode = 500;
    msg.payload = { success: false, message: 'Internal Server Error', code: 500, result: {} };
    return msg;
}
